package com.ipzoe.common.service;

import com.github.pagehelper.PageHelper;
import com.ipzoe.common.bean.entity.Admin;
import com.ipzoe.common.bean.response.Code;
import com.ipzoe.common.bean.response.PageBean;
import com.ipzoe.common.bean.response.Response;
import com.ipzoe.common.component.TokenComponent;
import com.ipzoe.common.repository.AdminRepository;
import com.ipzoe.common.util.DefaultService;
import lombok.extern.apachecommons.CommonsLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 后台管理员Service
 * <p>
 * Created 2018/01/18.
 *
 * @author pfzhang
 */
@Service
@Transactional(rollbackFor = RuntimeException.class)
@CommonsLog
public class AdminService extends DefaultService<Admin> {

    private AdminRepository adminRepository;

    @Resource
    public void setAdminRepository(AdminRepository adminRepository) {
        this.adminRepository = adminRepository;
        super.setDefaultMapper(adminRepository);
    }

    @Autowired
    private TokenComponent tokenComponent;

    @Autowired
    private AdminMenuService adminMenuService;

    /**
     * 后台管理员登录
     *
     * @param username 账户名
     * @param password 密码
     * @return 管理员对象
     */
    public Response<Admin> signIn(String username, String password) {
        Admin admin = adminRepository.findByUsername(username);
        if (admin == null || admin.getDelFlag()) {
            return Response.ok(Code.ADMIN_NOT_EXIST);
        }

        if (admin.getStatus().equals(Admin.STATUS_BLOCKED)) {
            return Response.ok(Code.ADMIN_BLOCK_ERROR);
        }

        if (!admin.getPassword().equals(password)) {
            return Response.ok(Code.ADMIN_PASSWORD_ERROR);
        }

        String token = tokenComponent.generateToken(admin.getId().toString(), admin.getRole().getName());
        admin.setToken("Bearer " + token);

        admin.setAdminMenusList(adminMenuService.generateAdminMenu(admin.getRole().getId(), 0, 0L));

        log.info("管理员[" + admin.getUsername() + "]登录,ID为" + admin.getId());

        return Response.ok(admin);
    }

    /**
     * 查询后台管理员
     *
     * @param key  搜索关键字
     * @param page 当前页
     * @param size 页面大小
     * @return 管理员集合分页对象
     */
    public Response<PageBean<Admin>> listAdmin(String key, int page, int size) {
        PageHelper.startPage(page, size);
        List<Admin> list = adminRepository.search("%" + key + "%");
        return Response.ok(new PageBean<>(list));
    }

    /**
     * 创建管理员
     *
     * @param username 用户名
     * @param roleId   角色ID
     * @return 接口响应对象
     */
    public Response create(String username, Long roleId) {
        Admin admin = adminRepository.findByUsername(username);
        if (null != admin) {
            return Response.error(Code.ADMIN_ALREADY_EXIST);
        }
        admin = new Admin();
        admin.setUsername(username);
        admin.setPassword(Admin.INIT_PASSWORD);
        admin.setRoleId(roleId);
        insertSelective(admin.getUsername(), admin);
        return Response.ok();
    }

    /**
     * 修改管理员
     *
     * @param adminId  管理员ID
     * @param username 用户名
     * @param roleId   角色ID
     * @return 接口响应对象
     */
    public Response update(Long adminId, String username, Long roleId) {
        if (1 != adminId) {
            Admin otherAdmin = adminRepository.findByUsername(username);
            if (null != otherAdmin && !otherAdmin.getId().equals(adminId)) {
                return Response.error(Code.ADMIN_ALREADY_EXIST);
            }
            Admin admin = selectById(adminId);
            if (null != admin && Admin.STATUS_NORMAL == admin.getStatus()) {
                admin.setRoleId(roleId);
                admin.setUsername(username);
                updateSelective(admin.getUsername(), admin);
            }
        }
        return Response.ok();
    }

    /**
     * 冻结/解冻
     *
     * @param adminId 管理员ID
     * @return 接口响应对象
     */
    public Response block(Long adminId) {
        Admin admin = selectById(adminId);
        if (admin == null) {
            return Response.ok(Code.ADMIN_NOT_EXIST);
        }

        if (admin.getStatus() == Admin.STATUS_NORMAL) {
            admin.setStatus(Admin.STATUS_BLOCKED);
        } else {
            admin.setStatus(Admin.STATUS_NORMAL);
        }
        updateSelective(admin.getUsername(), admin);

        return Response.ok();
    }
}
